import json

import requests
from requests import utils
import re
from unit_tools.handle_data.yaml_handler import read_yaml, write_yaml
from unit_tools.log_utils.recordlog import logs


class SendRequests:

    def __init__(self):
        pass

    @classmethod
    def _text_encode(cls, res_text):
        """
        处理接口返回值出现unicode编码，如：\\u767b\\f54fe;这里要用到正则校验，进行数据比对
        :param res_text:
        :return:
        """
        match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
        if match:
            result = res_text.encode().decode('unicode-escape')
        else:
            result = res_text
        return result

    def send_request(self, **kwargs):
        # 创建一个会话
        session = requests.session()
        response = None
        try:
            response = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            if set_cookie:
                write_yaml({'cookie':set_cookie})
            # 这里调用一下_text_encode方法，做编码处理
            res = self._text_encode(response.text)

        except requests.exceptions.ConnectionError:
            logs.error("接口请求异常，可能是request的连接数过多或者速度过快导致程序报错，或url不正确，header不正确等")
            # print("接口请求异常，可能是request的连接数过多或者速度过快导致程序报错，或url不正确，header不正确等")

        except requests.exceptions.RequestException as e:
            logs.error(f"请求异常，请检查系统或数据是否正常,原因：{e}")
            # print(f"请求异常，请检查系统或数据是否正常,原因：{e}")

        return response

    def excute_api_request(self, api_name, url, method, headers, case_name, cookies=None, files=None, **kwargs):
        """
        发起接口请求的方法
        :param api_name:接口名称
        :param url:接口地址
        :param method:请求方法
        :param headers:请求头
        :param case_name:测试用例名称
        :param cookies:cookies
        :param files:文件上传
        :param kwargs:未知数量的关键字参数
        :return:
        """
        logs.info(f'接口名称：{api_name}')
        logs.info(f'请求地址：{url}')
        logs.info(f'请求方式：{method.upper()}')
        logs.info(f'请求头：{headers}')
        logs.info(f'用例名称：{case_name}')
        logs.info(f'Cookies：{cookies}')
        yaml_params_type = kwargs.keys()
        if kwargs and ('data' in yaml_params_type or 'json' in yaml_params_type or 'params' in yaml_params_type):
            params_type = list(kwargs.keys())[0]
            logs.info(f'参数类型：{params_type}')
            params = json.dumps(list(kwargs.values())[0], ensure_ascii=False)
            logs.info(f'请求参数：{params}')

        response = self.send_request(method=method,
                                     url=url,
                                     headers=headers,
                                     cookies=cookies,
                                     files=files,
                                     timeout=10,
                                     verify=False,
                                     **kwargs)  # timeout=10超时设置为10s，varify=False取消证书验证
        return response


